package com.xinyue.start;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author 王广帅
 * @version 1.0.0
 * @since 2025/3/2 10:34
 */
@Service
@Slf4j
public class ServiceStartResultHandler implements ApplicationListener<ApplicationEvent>, SpringApplicationRunListener {
    private static ScheduledExecutorService executorService;

    private static final String FAILED_LOG_MSG = "====服务启动失败了,快修复一下吧====";

    @PostConstruct
    public void init() {
        executorService = Executors.newSingleThreadScheduledExecutor();
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 为了输出更多的错误日志，延迟打印这个日志
        executorService.schedule(() -> {
            if (event instanceof ApplicationFailedEvent) {
                log.error(FAILED_LOG_MSG);
            } else if (event instanceof ApplicationReadyEvent) {
                log.warn("====恭喜,服务启动成功====");
            }
        }, 5, TimeUnit.SECONDS);

    }

    public static void startFailed() {
        log.error(FAILED_LOG_MSG);
    }
}
